<?php

/*
 *  getMedia.php
 *  Written by: Letitia Lew
 *  
 *  A GET request to fetch all media from a certain trip_id.
 *  If you want media from a particular day, pass in the date
 *  in the format "YYYY-mm-dd"
 *  If you want a certain type of media, pass it in like 'photo'
 *  or 'video'
 */

require_once "../includes/db_lib.php";
require_once "../includes/media.php";


if (isset($_GET['trip_id']))
{
	echo "<html><head></head><body>";
	echo "<p>Processing xml of trip {$_GET['trip_id']}</p>";

	$db_conn = new DBConn();
	
	$xmlFile = fopen("flashData.xml", 'w') or die("fopen failure");
	$xmlContents = "";

	$xmlContents .= '<?xml version="1.0" encoding="utf-8" ?>';
	$xmlContents .= "\n";
	
    $query = "SELECT * FROM media WHERE trip_id = ". $db_conn->sanitize($_GET['trip_id']);
	
	if (isset($_GET['date'])) { // in format "YYYY-mm-dd"
      $query = $query." AND DATE(time_captured) = " . $db_conn->sanitize($_GET['date']);
    }
    
	$results = $db_conn->query($query);
	$num_results = mysqli_num_rows($results);

	// BEGIN MEDIA
	$xmlContents .= "<media>";
	$xmlContents .= "<total>{$num_results}</total>";	

	while ($row = mysqli_fetch_array($results, MYSQLI_ASSOC))
	{
		try {
			$media = new Media($row);
	    	$xmlContents .= "\n".$media->serialize();
		} catch (Exception $e) {
			// TODO: handle invalid media
			$num_results--;
		}
	}

	$xmlContents .= "</media>";
	// END MEDIA
	
	// write the generated XML to a file
	fwrite($xmlFile, $xmlContents);
	echo "<p>xml generated successfully!  ";
	echo "View it <a href='flashData.xml'>here</a></p>";
	echo "</body></html>";
	
	fclose($xmlFile);
}

?>
